<style>

.uploader{    
	border-radius: 5px;
    border: 1px solid #ddd;
    width: 100%;
    margin-bottom: 5px;
}
.uploader_body{
	width:100%;
	position: relative;
	border-top:1px solid #ddd;
	background: #eee;
}

.uploader_btn{
	
}
.uploader input[type="file"]{
	display: none
}
.uploader_empty{
	border: 1px #337ab7 dashed;
	height:180px;
	width:200px;
	margin:5px;
	padding: 5px 5px 30px 5px;
	box-sizing: content-box;
	border-radius: 4px;
	float: left;
}
.uploader_item{
	height:180px;
	width:200px;
	background-color: #fff;
	margin:5px;
	float: left;
	border: 1px #337ab7 solid;
	position:relative;
	padding: 5px 5px 30px 5px;
	box-sizing: content-box;
	border-radius: 4px;
	overflow: hidden;
}
.uploader_img_contian{
	width: 200px;
	height:176px;
	position: absolute;
	bottom:5px;
	left:5px;
	background-repeat: no-repeat;
	background-position: center;
	background-size: contain;
}
.uploader_item>i{
	font-style: normal;
	font-weight: bold;
	font-size: 16px;
	line-height: 180px;
	text-align: center
}
.uploader_tool>button{
	float: right;
	margin-left:3px;
}
.uploader_tool{
	width:100%;
	height:28px;
	position: absolute;
	top: 0;
	left: 0;
	padding: 3px 5px
}
.uploader_size{
	width: 145px;
	line-height: 25px;
	display: inline-block;
	cursor: all-scroll;
}
.uploader_progress{
	position: absolute;
	top:0;
	width:100%;
    left:0;
}
.uploader_draged{
	position:fixed;
	z-index: 9999;
}

.attr_body{border-radius: 5px;border: 1px solid #ddd;width: 100%;margin-bottom: 5px;}
.attr_content{width:100%;position: relative;border-top:1px solid #ddd;background: #eee;padding:0 10px;}
.attr_item{margin:10px 0;}
.attr_item_title{position: relative;}
.attr_btn_group{position:absolute;right:15px;top:5px;}
</style>
<form action="" method="post">
<div class="row" style="padding-top: 20px">
	<div class="col-lg-8">
		<div class="form-group">
			<label for="form_title">标题</label>
		    <input type="text" class="form-control" name="title" id="form_title" value="<?php echo isset($product)?$product['title']:'';?>">
		</div>
		

		<div class="form-group">
			<label for="form_uri">URL</label>
			<div class="input-group">
				<input type="text" class="form-control" name="uri" id="form_uri" value="<?php echo isset($product)?$product['uri']:'';?>">
				<span class="input-group-addon">.html</span>
			</div>
		</div>
		
		<div class="form-group">
			<label>展示图</label>
			<input type="text" style="display: none" id="form_img_banners" name="img_banners" value='<?php echo isset($product)?$product['img_banners']:'';?>'>
		</div>

		<div class="form-group">
			<label>属性</label>
			<input type="text" style="display: none" id="form_attr" name="attr" value='<?php echo isset($product)?$product['attr']:'[]';?>'>
		</div>

		<div class="form-group">
	  		<label for="form_content">商品详情</label>
	  	    <textarea class="form-control" id="form_content" name="content" rows="5"><?php echo isset($product)?$product['content']:'';?></textarea>
	  	</div>

	  	<div class="form-group">
	  		<label for="form_tip">购买提示</label>
	  	    <textarea class="form-control" id="form_tip" name="tip" rows="3"><?php echo isset($product)?$product['tip']:'';?></textarea>
	  	</div>

		<div class="form-group">
			<label for="form_fb_id">FB-ID</label>
		    <input type="text" class="form-control" name="fb_id" id="form_fb_id" value="<?php echo isset($product)?$product['fb_id']:'';?>">
		</div>
		
		<div class="form-group">
			<label for="form_seo_keywords">SEO关键词</label>
		    <input type="text" class="form-control" name="seo_keywords" id="form_seo_keywords" value="<?php echo isset($product)?$product['seo_keywords']:'';?>">
		</div>

		<div class="form-group">
			<label for="form_seo_descript">SEO描述</label>
		    <textarea class="form-control" id="form_seo_descript" name="seo_descript" rows="3"><?php echo isset($product)?$product['seo_descript']:'';?></textarea>
		</div>
		
		
	</div>
	<div class="col-lg-4">
		<div class="form-group">
		    <label for="form_host_id">域名</label>
		    <select class="form-control" name="host_id" id="form_host_id">
			<?php foreach ($host as $item):?>
			  <option value="<?=$item['id']?>" <?php echo isset($product)&&$product['host_id']==$item['id']?'selected':'';?>><?=$item['name']?></option>
			<?php endforeach;?>
			</select>
		</div>

		<div class="form-group">
		    <label for="form_location_id">地区</label>
		    <select class="form-control" id="form_location_id" name="location_id">
			  	<?php foreach ($location as $item):?>
				  <option value="<?=$item['id']?>" <?php echo isset($product)&&$product['location_id']==$item['id']?'selected':'';?>><?=$item['name']?></option>
				<?php endforeach;?>
			</select>
		</div>

		<div class="form-group">
		    <label for="form_lang_id">语言</label>
		    <select class="form-control" id="form_lang_id" name="lang_id">
		    <?php foreach ($lang as $item):?>
			  <option value="<?=$item['id']?>" <?php echo isset($product)&&$product['lang_id']==$item['id']?'selected':'';?>><?=$item['name']?></option>
			<?php endforeach;?>
			</select>
		</div>
		
		<div class="form-group">
		    <label for="form_currency_id">货币</label>
		    <select class="form-control" id="form_currency_id" name="currency_id">
			  	<?php foreach ($currency as $item):?>
			  		<option value="<?=$item['id']?>" <?php echo isset($product)&&$product['currency_id']==$item['id']?'selected':'';?>><?=$item['name']?></option>
				<?php endforeach;?>
			</select>
		</div>

		<div class="form-group">
			<label id="form-theme">模板</label>
			<select class="form-control" name="theme" id="form_theme">
			<?php foreach ($theme as $item):?>
			  <option value="<?=$item['path']?>" <?php echo isset($product)&&$product['theme']==$item['path']?'selected':'';?>><?=$item['title']?></option>
			<?php endforeach;?>
			</select>
		</div>

		<div class="form-group">
			<label for="form_price">价格</label>
		    <input type="number" class="form-control" id="form_price" name="price" value="<?php echo isset($product)?$product['price']:'';?>">
		</div>
		<div class="form-group">
			<label for="form_discount_price">优惠价</label>
			<div class="input-group">
		      <span class="input-group-addon">
		        <input type="checkbox" value="1" name="is_discount" <?php echo isset($product)&&$product['is_discount']?'checked':'';?>>
		      </span>
		      <input type="number" id="form_discount_price" name="discount_price" class="form-control" value="<?php echo isset($product)?$product['discount_price']:'';?>">
		    </div>
		</div>
	</div>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
<script type="text/javascript">

$.fn.fileUpload = function(config){
	var upload_main = $('<div class="uploader"></div>');
	var upload_body = $('<div class="clearfix uploader_body"></div>');
	var upload_btn = $('<button class="btn btn-primary uploader_btn" type="button"><span class="glyphicon glyphicon-picture" aria-hidden="true"></span>  添加</button>');
	var upload_selecter = $('<input type="file" title="选择图片" accept="image/jpeg,image/png"/>');
	upload_main.append(upload_btn).append(upload_body).append(upload_selecter).css('width',config.width?config.width:'100%');
	$(this).after(upload_main);
	upload_btn.click(function(){
		upload_selecter.click();
	});
	var main_input = $(this);
	var setValue = function(){
		var value = [];
		upload_body.children('.uploader_item').each(function(k,item){
			value.push(JSON.parse($(item).attr('upload_data')));
		})
		main_input.val(JSON.stringify(value));
	}
	var add_image = function(data){
		var imgItem = $('<div class="uploader_item"><div class="uploader_img_contian" style="background-image:url('+data.path+')"></div></div>');
		var img_tool = $('<div class="uploader_tool bg-primary"></div>');
		var btn_dele = $('<button type="button" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-trash"></span></button>');
		var btn_view = $('<button type="button" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button>');
		var img_size = $('<span class="uploader_size">'+data.size+'kb</span>');
		img_tool.append(img_size).append(btn_view).append(btn_dele);
		imgItem.append(img_tool).attr('upload_data',JSON.stringify(data));
		btn_dele.on('click',function(){
			if(upload_body.children().length>=6){
				bs_alert('最多只能上传6张图片！');
				return;
			}
			imgItem.remove();
			setValue();
		});
		btn_view.on('click',function(){
			layer.open({
			  type: 1,
			  title: false,
			  closeBtn: 0,
			  area:[data.width+'px',data.height+'px'] ,
			  shadeClose: true,
			  content: '<img style="display:block" src="'+data.path+'" />'
			});
		})
		img_size.on('mousedown',function(e){
			var disX = e.clientX - imgItem.offset().left;
			var disY = e.clientY - imgItem.offset().top;
			var empty = $('<div class="uploader_empty"></div>');
			imgItem.css({'left':imgItem.offset().left-5,'top':imgItem.offset().top-5}).addClass('uploader_draged').after(empty);
			var index = imgItem.index('.uploader_item');
			$(document).on({
				mousemove:function(e){
					if(!imgItem.hasClass('uploader_draged')) return;
					imgItem.css({'left':e.clientX-disX,'top':e.clientY-disY});
					var hover = $(document.elementFromPoint(e.clientX-disX,e.clientY-disY));
					if(hover.hasClass('uploader_size')){
						var hoverItem = hover.parent().parent();
						var hoverIndex = hoverItem.index('.uploader_item');
						hoverIndex>index?hoverItem.after(empty):hoverItem.before(empty);
					}else if(!hover.hasClass('uploader_empty')){
						imgItem.after(empty);
					}
				},	
				mouseup:function(){
					if(imgItem.hasClass('uploader_draged')){
						imgItem.removeClass('uploader_draged').css({'left':0,'top':0});
						upload_body.children('.uploader_empty').after(imgItem).remove();
						$(this).off('mousemove').off('mouseup');
						setValue();
					}
				}
			})
		});
		return imgItem;
	}
	if($(this).val()!=''){
		var preValueArr = JSON.parse($(this).val());
		$.each(preValueArr,function(k,v){
			upload_body.append(add_image(v));
		});
	}
	upload_selecter.change(function(){
		var xhrOnProgress=function(fun) {
	  		xhrOnProgress.onprogress = fun;
	  		return function() {
		    	var xhr = $.ajaxSettings.xhr();
		    	if(typeof xhrOnProgress.onprogress !== 'function') return xhr;
		    	if(xhrOnProgress.onprogress && xhr.upload){
		      		xhr.upload.onprogress = xhrOnProgress.onprogress;
		    	}
		    	return xhr;
		  	}
		};
		var imgItem = $('<div class="uploader_item"><i class="text-primary center-block"></i><div class="progress uploader_progress"><div class="progress-bar" style="width: 0%;"></div></div></div>');
		upload_body.append(imgItem);
		var data = new FormData();
		data.append('upload_file',this.files[0]);
		if(typeof(ie)=='undefined') {
        	$(this).val('');
		} else {
		    $(this).replaceWith($(this).clone(true));
		}
		$.ajax({
            url:config.uploadUrl,
            type:'POST',
            data:data,
            cache: false,
            contentType: false,
            processData: false,
            success:function(data){
            	if(data.statu=='ok'){
            		imgItem.after(add_image(data.result)).remove();
            		setValue();
            	}else{
            		bs_alert(data.message,function(){
            			imgItem.remove();
            		});
            	}
            },
            error:function(){
            	bs_alert('上传失败！',function(){
            		imgItem.remove();
            	});
            },
            xhr:xhrOnProgress(function(e){
            	var i = imgItem.children('i');
            	var progrss = imgItem.find('.progress-bar');
			    var percent=parseInt(e.loaded*100/e.total)+'%';
			    i.text(percent);
			    progrss.css('width',percent);
			})
        });
        
	})
}

$.fn.attrParse = function(){
	var main_input = $(this);
	var attr_body = $('<div class="attr_body"></div>')
	var attr_add_btn = $('<button class="btn btn-primary" type="button"><span class="glyphicon glyphicon-pushpin" aria-hidden="true"></span>  添加</button>');
	var attr_content = $('<div class="attr_content"></div>');
	attr_body.append(attr_add_btn).append(attr_content);
	$(this).after(attr_body);
	
	attr_add_btn.click(function(){
		if(attr_content.children('div.attr_item').length>=4){
			layer.msg('最多只能添加4个属性！', {icon: 2});
		    return;
		}
		var prompt = layer.prompt({title: '请输入属性名称', formType: 0,value:name}, function(text, index){
		    text = $.trim(text);
		    if(text.length<1||text.length>10){
		    	layer.msg('请输入1-10个字符！', {icon: 2});
		    	return;
		    }
		    layer.close(prompt);
		    addAttr(text);
		    dom2val();
		});
	});

	var addAttr = function(name){
		var item_box = $('<div class="panel panel-primary attr_item" data-name="'+name+'"></div>');
	    var item_title = $('<div class="panel-heading attr_item_title">'+name+'</div>');
	    var btn_group = $('<div class="btn-group btn-group-sm attr_btn_group"></div>');
	    var btn_add = $('<button type="button" class="btn btn-success">添加值</button>');
	    var btn_dele = $('<button type="button" class="btn btn-danger">删除属性</button>');
	    var table = $('<table class="table"></table>');
	    var table_head = $('<thead><tr><th>值</th><th width="100">差价</th><th width="180">操作</th></tr></thead>');
	    var table_body = $('<tbody></tbody>');
	    btn_group.append(btn_add).append(btn_dele);
	    item_title.append(btn_group);
	    table.append(table_head).append(table_body);
	    item_box.append(item_title).append(table)
	    attr_content.append(item_box);
	    btn_add.click(function(){
	    	var html = '<form id="location_form">'+makeInput({name:'value',label:'值',value:'',type:'text'})+makeInput({name:'price_add',label:'差价',value:'0',type:'number'})+'</form>';
			layer.open({
			    title:'新增'+name,
			    area: ['520px'], //宽高
			    content: html,
			    btn:['提交','取消'],
			    yes:function(index){
			      var data = $("#location_form").serializeArray();
			      var result = {};
			      $.each(data,function(k,v){
			      	result[v.name] = $.trim(v.value);
			      })
			      if(result.value.length<1||result.value.length>30){
			      	layer.msg('值为1-10个字符！', {icon: 2});
		    		return;
			      }
			      if(result.price_add<0||result.price_add>100000){
			      	layer.msg('差价为1-100000！', {icon: 2});
		    		return;
			      }
			      layer.close(index);
			      addItem(table_body,result);
			      dom2val();
			    }
			});
	    })
	    btn_dele.click(function(){
	    	var confirm = layer.confirm('确定删除？', 
	    	{btn: ['确定','取消']}, 
	    	function(){
	    		item_box.remove();
			    layer.close(confirm);
			    dom2val();
			});
	    });
	    
	    return item_box;
	}

	var addItem = function(tbody,data){
		var btn_group = $('<div class="btn-group btn-group-sm"></div>');
	    var btn_edit = $('<button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-edit"></span></button>');
	    var btn_dele = $('<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span></button>');
	    var item = $('<tr data-value="'+data.value+'" data-price-add="'+data.price_add+'"><td>'+data.value+'</td><td>'+data.price_add+'</td></tr>');
	    var td = $('<td></td>');
	    btn_group.append(btn_edit).append(btn_dele);
	    td.append(btn_group);
	    item.append(td);
		tbody.append(item);
		btn_edit.click(function(){
			var html = '<form id="location_form">'+makeInput({name:'value',label:'值',value:item.data('value'),type:'text'})+makeInput({name:'price_add',label:'差价',value:item.data('price-add'),type:'number'})+'</form>';
			layer.open({
			    title:'编辑-'+name,
			    area: ['520px'], //宽高
			    content: html,
			    btn:['提交','取消'],
			    yes:function(index){
			      var data = $("#location_form").serializeArray();
			      var result = {};
			      $.each(data,function(k,v){
			      	result[v.name] = $.trim(v.value);
			      })
			      if(result.value.length<1||result.value.length>30){
			      	layer.msg('值为1-10个字符！', {icon: 2});
		    		return;
			      }
			      if(result.price_add<0||result.price_add>100000){
			      	layer.msg('差价为1-100000！', {icon: 2});
		    		return;
			      }
			      layer.close(index);
			      item.data('value',result.value).data('price-add',result.price_add);
			      var tds = item.children();
			      tds.eq(0).html(result.value);
			      tds.eq(1).text(result.price_add);
			      dom2val();
			    }
			});
		});
		btn_dele.click(function(){
			item.remove();
			dom2val();
		})
		return item;
	}

	var dom2val = function(){
		var attrArry = [];
		attr_content.children('div.attr_item').each(function(){
			var attrObj = {};
			attrObj.name = $(this).data('name');
			attrObj.option = [];
			$(this).find('tbody').children().each(function(){
				var option = {};
				option.value = $(this).data('value');
				option.price_add = $(this).data('price-add');
				attrObj.option.push(option);
			})
			attrArry.push(attrObj); 
		})
		main_input.val(JSON.stringify(attrArry));
	}

	var attrArry = JSON.parse(main_input.val());
	$.each(attrArry,function(key,attrObj){
		var item_box = addAttr(attrObj.name);
		$.each(attrObj.option,function(k,v){
			addItem(item_box.find('tbody'),v);
		});
	});

		
}

function makeInput(config){//type value name label
  var inputStr = '<div class="form-group">';
  inputStr+='<label for="form_'+config.name+'">'+config.label+'</label>';
  inputStr+='<input type="'+config.type+'" class="form-control" name="'+config.name+'" id="form_'+config.name+'" value="'+config.value+'"></div>';
  return inputStr;
}

function sendFile(file){  
    var filename = false;  
    try{  
      filename = file['name'];  
    } catch(e){  
        filename = false;  
    }  
    if(!filename){  
        $(".note-alarm").remove();  
    }  
    data = new FormData();
    data.append('upload_file',file);  
    $.ajax({  
      data: data,  
      type: "POST",  
      url: "<?php echo site_url('api/upload/image_product_shows');?>", 
      contentType: false,  
      processData: false,  
      success: function(data){
        console.log(data)
        if(data.statu=='ok'){
          editer.summernote('insertImage',data.result.path,'');
        }else{
          bs_alert(data.message);
        }
      },  
      error:function(){  
          bs_alert('上传失败！');  
      }  
    });  
 }
var editer = $('#form_content');
$(function(){
	$("#form_img_banners").fileUpload({
		uploadUrl:'/api/upload/image_product_shows.html',
		width:'100%'
	});
  	
	$("#form_attr").attrParse();
	editer.summernote({
        height: 500,  
        focus: true,
        tabsize: 2,
        lang: 'zh-CN',
        placeholder: '写点什么,或者上传图片...',
        callbacks: {
          onImageUpload: function(files) {
            sendFile(files[0]);
          }
        }
  	});
})
</script>